package com.bh.springbootjdk17demo.example;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse;

/**
 * @author sy
 * @version 1.0
 * @description POST
 */
@Slf4j
public class HttpClientPostExample {

    public static void main(String[] args) {
        HttpClient client = HttpClient.newHttpClient();

        //要发送的JSON数据
        String jsonData = "{\"title\":\"foo\",\"body\":\"bar\",\"userId\":1}";
        //创建一个 HttpRequest 实例，指定方法为POST，并设置目标URI和请求体
        HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://localhost:8006/sjzd/getMsgByPost"))
                .headers("Content-Type", "application/json").POST(BodyPublishers.ofString(jsonData)).build();
        try {
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            log.info("==Response Code:{}==",response.statusCode());
            log.info("==Response Body:{}==",response.body());
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
